<template>
    <van-popup v-model:show="isUserSelectorShow" position="bottom" style="height: 70vh;" @open="showUserSelector()"
        @close="closeUserSelector()">
        <van-tabs v-model:active="activeTab">
            <van-tab title="选择班组成员" name="选择班组成员">
                <van-search v-model="sameDepartmentUser" placeholder="请输入搜索关键词" show-action
                    @search="searchSameDepartmentUsers" @clear="clearSameDepartmentUsers">
                    <template #action>
                        <div @click="searchSameDepartmentUsers">搜索</div>
                    </template>
                </van-search>
                <div class="selection-controls" v-if="!props.noCheckbox">
                    <van-button size="small" type="primary" @click="checkAllUsers">
                        全选
                    </van-button>
                    <van-button size="small" type="warning" @click="invertAllSelected">
                        反选
                    </van-button>
                </div>
                <van-loading v-if="loading" color="#409EFF" size="30" class="loading-container" />
                <div class="tab-content-container" v-else>
                    <van-cell-group inset v-if="!props.noCheckbox" v-for="(item, index) in filteredSameDepartmentUsers">
                        <van-cell clickable :key="item.id" :title="item.name" :label="item.no"
                            @click="toggleSelection(item)" :class="{ 'selected': isSelected(item.id) }">
                        </van-cell>
                    </van-cell-group>
                    <van-cell-group inset v-else v-for="(item, index) in filteredSameDepartmentUsers">
                        <van-cell clickable :key="item.id" :title="item.name" :value="item.no" @click="fillUser(item)">
                        </van-cell>
                    </van-cell-group>
                </div>
            </van-tab>
            <van-tab title="全部" name="全部">
                <van-search v-model="allDepartmentUser" placeholder="请输入搜索关键词" show-action @search="searchUser"
                    @clear="clearUsers">
                    <template #action>
                        <div @click="searchUser">搜索</div>
                    </template>
                </van-search>
                <div class="search-result-list" v-if="filteredSearchResults.length > 0">
                    <van-cell-group class="popup-van-cell-group" v-for="(result, index) in filteredSearchResults"
                        v-if="props.noCheckbox">
                        <van-cell :key="index" :title="result.name" :value="result.no" :label="result.departmentName"
                            @click="fillUser(result)" />
                    </van-cell-group>
                    <van-cell-group class="popup-van-cell-group" v-for="(result, index) in filteredSearchResults"
                        v-else>
                        <van-cell :key="index" :title="result.name" :value="result.no" :label="result.departmentName"
                            @click="toggleSelection(result)" :class="{ 'selected': isSelected(result.id) }" />
                    </van-cell-group>
                </div>
                <div class="search-result-nothing" v-else>未找到匹配的人员</div>
            </van-tab>
        </van-tabs>
    </van-popup>
    <van-floating-bubble icon="success" v-if="isUserSelectorShow && !props.noCheckbox && selectedUserIds.length > 0"
        style="z-index: 9999;" @click="fillUsers">
    </van-floating-bubble>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { showLoadingToast, closeToast, showFailToast, showToast } from 'vant';
import useStore from '@/store/index';
const store = useStore();
import { errorNotify } from "@/utils/Misc";
const props = defineProps(["noCheckbox", "excludeUserIds"])
const emit = defineEmits(["fillUser", "fillUsers"]);
import userAPI from "@/api/user";
const isUserSelectorShow = ref(false);
const allDepartmentUser = ref("")
const sameDepartmentUser = ref("")
const sameDepartmentUsers = ref([])
const originalSameDepartmentUsers = ref([])
const selectedUsers = ref([])
const selectedUserIds = ref([]);
const searchUserResults = ref([])
const activeTab = ref()
const loading = ref(false)
const setSelectedUserIds = (data) => {
    selectedUserIds.value = data
};
const filteredSameDepartmentUsers = computed(() => {
    return sameDepartmentUsers.value.filter(user =>
        !props.excludeUserIds || !props.excludeUserIds.includes(user.id)
    );
});
const filteredSearchResults = computed(() => {
    return searchUserResults.value.filter(user =>
        !props.excludeUserIds || !props.excludeUserIds.includes(user.id)
    );
});
const showUserSelector = async () => {
    isUserSelectorShow.value = true;
    activeTab.value = "选择班组成员";
    loading.value = true;
    const userRes = await userAPI.getUserInfo({
        departmentId: store.user.departmentId,
    });
    loading.value = false;
    sameDepartmentUsers.value = userRes.data.page.list;
}
const closeUserSelector = () => {
    selectedUserIds.value = [];
    sameDepartmentUser.value = "";
    allDepartmentUser.value = "";
    sameDepartmentUsers.value = JSON.parse(JSON.stringify(originalSameDepartmentUsers.value));
};
const toggleSelection = (user) => {
    const idIndex = selectedUserIds.value.indexOf(user.id);
    const userIndex = selectedUsers.value.findIndex(u => u.id === user.id);
    if (idIndex > -1) {
        selectedUserIds.value.splice(idIndex, 1);
    } else {
        selectedUserIds.value.push(user.id);
    }
    if (userIndex > -1) {
        selectedUsers.value.splice(userIndex, 1);
    } else {
        selectedUsers.value.push(user);
    }
};
const isSelected = (userId) => {
    return selectedUserIds.value.includes(userId)
};
const fillUsers = () => {
    isUserSelectorShow.value = false;
    emit("fillUsers", selectedUsers.value);
    selectedUserIds.value = [];
};
const checkAllUsers = () => {
    const filteredUsers = filteredSameDepartmentUsers.value;
    if (filteredUsers.length === 0) return;
    const usersToAdd = filteredUsers.filter(user => !selectedUserIds.value.includes(user.id));
    if (usersToAdd.length === 0) return;
    selectedUserIds.value = [...selectedUserIds.value, ...usersToAdd.map(u => u.id)];
    selectedUsers.value = [...selectedUsers.value, ...usersToAdd];
};
const invertAllSelected = () => {
    const filteredUsers = filteredSameDepartmentUsers.value;
    if (filteredUsers.length === 0) return;
    const userIdsToToggle = filteredUsers.map(u => u.id);
    const usersToAdd = [];
    const usersToRemove = [];
    filteredUsers.forEach(user => {
        if (selectedUserIds.value.includes(user.id)) {
            usersToRemove.push(user.id);
        } else {
            usersToAdd.push(user);
        }
    });
    selectedUserIds.value = [
        ...selectedUserIds.value.filter(id => !usersToRemove.includes(id)),
        ...usersToAdd.map(u => u.id)
    ];
    selectedUsers.value = [
        ...selectedUsers.value.filter(user => !usersToRemove.includes(user.id)),
        ...usersToAdd
    ];
};
const searchSameDepartmentUsers = () => {
    if (originalSameDepartmentUsers.value.length == 0) {
        originalSameDepartmentUsers.value = JSON.parse(JSON.stringify(sameDepartmentUsers.value));
    }
    const keyword = sameDepartmentUser.value.trim().toLowerCase();
    sameDepartmentUsers.value = originalSameDepartmentUsers.value.filter(user => {
        const nameMatch = user.name.toLowerCase().includes(keyword);
        const noMatch = user.no.toLowerCase().includes(keyword);
        return nameMatch || noMatch;
    });
};
const clearSameDepartmentUsers = () => {
    sameDepartmentUser.value = "";
    sameDepartmentUsers.value = JSON.parse(JSON.stringify(originalSameDepartmentUsers.value));
};
const clearUsers = () => {
    allDepartmentUser.value = "";
};
const searchUser = async () => {
    showLoadingToast({
        message: '搜索中...',
        forbidClick: true,
        duration: 0
    });
    userAPI.getUserInfoFuzzy(allDepartmentUser.value).then(res => {
        closeToast();
        searchUserResults.value = [...searchUserResults.value, ...res.data.sysUserList]
    }).catch((error) => {
        errorNotify('UserSelector', 'searchUser', error);
    })
};
const fillUser = (user) => {
    isUserSelectorShow.value = false;
    emit("fillUser", user);
};
defineExpose({
    showUserSelector,
    setSelectedUserIds
})
</script>
<style scoped>
.popup-van-cell-group {
    margin: 0;
    width: auto;
    border: none;
    border-radius: 0;
    margin-bottom: 0;
}

.popup-content {
    padding: 0 1rem 0 1rem;
}

.search-button {
    border-radius: 10px;
    background-color: green;
    border-color: green;
}

.search-result-list {
    max-height: calc(70vh - 6.25rem);
    overflow-y: auto;
}

.search-result-nothing {
    text-align: center;
    color: #999;
    margin-top: 10px;
}

.tab-content-container {
    max-height: calc(70vh - 6.25rem);
    overflow-y: auto;
}

.selected {
    background-color: #E0F0FF;
}

.button-group {
    display: flex;
    gap: 1rem;
    padding: 1rem;
    background-color: #fff;
    border-top: 1px solid #eee;
}

.reset-btn,
.confirm-btn {
    flex: 1;
    height: 3rem;
    font-size: 1.1rem;
}

.reset-btn {
    background-color: #f5f5f5;
    color: #333;
}

:deep(.van-badge) {
    position: absolute;
    top: -5px;
    right: -5px;
}

.loading-container {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.selection-controls {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 10px 16px 0 16px;
    gap: 10px;
}
</style>
